package com.ruix.app.ui.stratum;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.OSS;
import com.ruix.app.R;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.OssTokenMapper;
import com.ruix.app.mapper.TagsMapper;
import com.ruix.app.model.Classes;
import com.ruix.app.model.OssToken;
import com.ruix.app.network.ALUploadFileParam;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.adapter.PhotoAdapter;
import com.ruix.app.ui.adapter.PostPhotoAdapter;
import com.ruix.app.ui.adapter.RecyclerItemClickListener;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.ImageClipUtil;
import com.ruix.app.util.RegUtil;
import com.ruix.app.util.SoftInputUtil;
import com.ruix.app.util.TackPicUtil;
import com.ruix.app.widget.CommonTitleBar;
import com.ruix.app.widget.ReleasePostTagView;
import com.ruix.app.widget.dialog.CommonDialog;
import com.ruix.app.widget.dialog.fragment.ListDialogFragment;
import com.ruix.app.widget.dialog.iface.IListDialogListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;

/**
 * Created by hadexs on 2017/4/21.
 */

public class ReleasePostsActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, IListDialogListener,ReleasePostTagView.ReleasePostTagViewListener {

    public static Intent newIntent(Context context, Classes classes) {
        Intent intent = new Intent(context, ReleasePostsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("classes", classes);
        intent.putExtras(bundle);
        return intent;
    }

    //图片选择
    private EditText inputEditText;
    private Classes currentClasses;
    private PostPhotoAdapter photoAdapter;
    private RecyclerView recyclerView;
    private OSS ossClient;
    private OssToken ossToken;
    private CommonTitleBar titleBar;
    private ReleasePostTagView tagView;


    private ArrayList<String> selectedPhotos = new ArrayList<>();

    private GridView  chosePicGridView;

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_release_posts;
    }

    @Override
    protected void initView() {
        titleBar = (CommonTitleBar) findViewById(R.id.nav);
        titleBar.setTitle("发布");
        //
//        View headerView =  View.inflate(this,R.layout.layout_release_post_header,null);
//        inputEditText = (EditText) headerView.findViewById(R.id.et_post_content);


        inputEditText = (EditText) findViewById(R.id.et_content);
//        inputEditText.requestFocus();
        inputEditText.setImeOptions(EditorInfo.IME_ACTION_DONE);
//        chosePicGridView =  (GridView)findViewById(R.id.gv_chose_picture);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        photoAdapter = new PostPhotoAdapter(this, selectedPhotos);

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, OrientationHelper.VERTICAL));
        recyclerView.setAdapter(photoAdapter);
//        chosePicGridView.setAdapter(photoAdapter);

         tagView = (ReleasePostTagView) findViewById(R.id.tag_bottom_view);

        TextView titleBarRightBtn = titleBar.getRightBtn();
        titleBarRightBtn.setText("发送");
        titleBarRightBtn.setTextColor(getResources().getColor(R.color.green));
        titleBarRightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                releasePost();
            }
        });

    }




    @Override
    protected void initListener() {
        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
                new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        if (photoAdapter.getItemViewType(position) == PhotoAdapter.TYPE_ADD) {
                            showDialog();
                        } else {
                            PhotoPreview.builder()
                                    .setPhotos(selectedPhotos)
                                    .setCurrentItem(position)
                                    .start(ReleasePostsActivity.this);
                        }
                    }
                }));

        inputEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tagView.hideTagsContain();
            }
        });

        if (titleBar != null){
            titleBar.setOnClickLeftListener(new CommonTitleBar.OnTitleBarClickLeftListener() {
                @Override
                public void onClickLeftBackBtn() {
                    checkInput();
                }
            });
        }

        tagView.setListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

        }

    }

    private void showSoftInput(){
        tagView.hideTagsContain();
        SoftInputUtil.showSoftInput(this,inputEditText); //显示输入框
    }

    public void addTag(String tag){
//        inputEditText.setSelection(inputEditText.getText().length());
        if (!TextUtils.isEmpty(tag)) {
            int index = inputEditText.getSelectionStart();
            Editable editable = inputEditText.getText();
            editable.insert(index, tag);
        }
    }

    @Override
    public void clickAddPhotoView() {
        showDialog();
    }

    @Override
    public void clickAddTagView() {
        SoftInputUtil.hideSoftInput(inputEditText);
    }

    public void addNewTag(){
        int index = inputEditText.getSelectionStart();
        Editable editable = inputEditText.getText();
        editable.insert(index, "##");
        int selectionPosition = index + 1;
        inputEditText.setSelection(selectionPosition);
        tagView.hideTagsContain();
        SoftInputUtil.showSoftInput(this,inputEditText); //显示输入框
    }



    @Override
    protected void initLocalData() {
        Intent intent = getIntent();
        if (intent != null) {
            currentClasses = (Classes) intent.getSerializableExtra("classes");
        }
        loadOssTokenWithCache();
        loadTags();

    }

    private void loadTags(){
        RequestFactory.postTag(currentClasses.getID(), new TagsMapper(), new RXObserver<ArrayList<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<String> value) {
                if (value != null) {
                    tagView.addTags(value);
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    private void loadOssTokenWithCache() {
        String uid = UserManager.getCurrentUser().getID();
        ossToken = CacheFactory.loadOssToken(uid);
        if (ossToken != null && !TextUtils.isEmpty(ossToken.getSecurityToken())) {
            buildOssClient();
        } else {
            loadOssToken();
        }
    }

    private void buildOssClient() {
        if (ossToken != null) {
            ossClient = ALUploadFileParam.loadOSSClient(this, ossToken);
        }
    }

    private void loadOssToken() {
        RequestFactory.getOssToken(new OssTokenMapper(), new RXObserver<OssToken>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OssToken value) {
                if (value != null && !TextUtils.isEmpty(value.getSecurityToken())) {
                    ossToken = value;
                    buildOssClient();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }



    private void checkInput(){
        if (selectedPhotos != null && selectedPhotos.size() > 0) {
            exitTipDialog();
            return;
        }
        String inputContent =  inputEditText.getText().toString();
        if (!TextUtils.isEmpty(inputContent)){
            exitTipDialog();
            return;
        }
        finish();
    }

    private void exitTipDialog(){
        CommonDialog dialog = new CommonDialog(this);
        dialog.setListener(new CommonDialog.CommonDialogAcitonListener() {
            @Override
            public void positiveAction() {
                if (inputEditText != null) {
                    SoftInputUtil.hideSoftInput(inputEditText);
                }
                finish();
            }

            @Override
            public void negertivieAction() {

            }
        });
        dialog.show("有未发布内容，是否退出");
        dialog.setPositiveString("是");
        dialog.seCancelString("否");
    }



    private void releasePost() {
        String postsContent = inputEditText.getText().toString();
        if (!TextUtils.isEmpty(postsContent)){
            if (!RegUtil.isLessThanLength(postsContent,4000)){
                showErrorTip("内容只能包含至多4000个字符");
                return;
            }
        }

        if (selectedPhotos != null && selectedPhotos.size() > 0) {
            uploadPhoto();
        } else {
//            String postsContent = inputEditText.getText().toString();
            if (TextUtils.isEmpty(postsContent)) {
                showErrorTip("请输入实践");
                return;
            }
            showLoading();
            releasePost(null);
        }
    }


    private void releasePost(ArrayList<String> value) {
        String source;
        if (value != null) {
            source = bulidFileSource(value);
        } else {
            source = "";
        }
        String postsContent = inputEditText.getText().toString();
        RequestFactory.publishPosts(currentClasses.getID(), postsContent, source, null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                sendReleasePostSuccess();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
            }

            @Override
            public void onComplete() {
                dismissLoading();
                showSuccessTip("发布成功");
                finish();
            }
        });

    }

    //上传图片
    private void uploadPhoto() {
        showLoading();//
        ALUploadFileParam param = new ALUploadFileParam();
        param.setUid(UserManager.getCurrentUser().getID());
        param.setPathes(selectedPhotos);
        param.setOssClient(ossClient);
        param.setOssToken(ossToken);
        RequestFactory.uploadFileToALY(param, new RXObserver<ArrayList<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<String> value) {
                releasePost(value);
            }

            @Override
            public void onError(Throwable e) {
//                showErrorTip(e.getMessage());
                showErrorTip("网络在开小差，检查后再试吧");
                dismissLoading();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private String bulidFileSource(ArrayList<String> value) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < value.size(); i++) {
            sb.append(value.get(i));
            if (i < value.size() - 1) {
                sb.append(",");
            }
        }
        return sb.toString();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK &&
                (requestCode == PhotoPicker.REQUEST_CODE || requestCode == PhotoPreview.REQUEST_CODE)) {

            List<String> photos = null;
            if (data != null) {
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            }
            selectedPhotos.clear();
            if (photos != null) {
                selectedPhotos.addAll(photos);
            }
            photoAdapter.notifyDataSetChanged();
        } else if (requestCode == CAMERA_WITH_DATA && resultCode == RESULT_OK) {
            if (cameraImgUri != null) {
                if (android.os.Build.VERSION.SDK_INT < 24) {
                    selectedPhotos.add(cameraImgUri.getPath());
                } else  {
                    try {
                       String path = TackPicUtil.getFilePathWithUri(cameraImgUri,this);
                        if (!TextUtils.isEmpty(path)) {
                            path =  Environment.getExternalStorageDirectory().getAbsolutePath() + path;
                            selectedPhotos.add(path);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            photoAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        checkCameraPermission();
    }

    private void sendReleasePostSuccess() {
        Intent intent = new Intent();
        intent.setAction(RuiXConstant.NOTICE_RELEASE_POST_SUCCESS);//RuiXConstant.NOTICE_CHANGE_SHARE_STATE
        sendOrderedBroadcast(intent, null);

        if (inputEditText != null) {
            SoftInputUtil.hideSoftInput(inputEditText);
        }
    }


    //
    private final int DIALOG_REQUEST_CODE_SET_AVATAR = 0x02;
    private Uri cameraImgUri;
    private final int CAMERA_WITH_DATA = 1001;
    private final int REQUEST_CODE_CAMERA = 222;

    //选择照片
    private void showDialog() {
        String[] choosePic = new String[2];
        choosePic[0] = "照相";
        choosePic[1] = "从手机相册选择";
        ListDialogFragment.createBuilder(this)
                .setTitle("选择图片来源")
                .setPositiveButtonText(R.string.confirm)
                .setNegativeButtonText(R.string.cancel)
                .setItems(choosePic)
                .setSelectedItem(0)
                .setRequestCode(DIALOG_REQUEST_CODE_SET_AVATAR)
                .show();
    }


    @Override
    public void onListItemSelected(CharSequence value, int number, int requestCode) {
        switch (requestCode) {
            case DIALOG_REQUEST_CODE_SET_AVATAR:
                if (number == 0) {
                    checkCameraPermission();
                } else {
                    PhotoPicker.builder()
                            .setPhotoCount(9)
                            .setShowCamera(true)
                            .setPreviewEnabled(false)
                            .setSelected(selectedPhotos)
                            .start(ReleasePostsActivity.this);
                }
                break;
        }
    }

    private void takePic() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// TODO: 16/5/26  没有外置存储
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            cameraImgUri = Uri.parse(Uri.fromFile(new File(ImageClipUtil.getCameraFileName(this))).toString());
            if (android.os.Build.VERSION.SDK_INT < 24) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImgUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                File file=new File(Environment.getExternalStorageDirectory(), "/temp/"+System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                cameraImgUri = FileProvider.getUriForFile(this.getApplicationContext(), "com.ruix.app.fileprovider", file);//通过FileProvider创建一个content类型的Uri
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImgUri);//将拍取的照片保存到指定URI

                //相同解决方案
//                ContentValues contentValues = new ContentValues(1);
//                contentValues.put(MediaStore.Images.Media.DATA, ImageClipUtil.getCameraFileName(this));
//                Uri uri = getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
//                cameraImgUri = uri;
//                Log.e("cameraImgUri","cameraImgUri"+cameraImgUri);
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } else {
            showErrorTip("暂不支持");
        }
    }


    private void checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            int aPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED || aPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(ReleasePostsActivity.this, new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_CAMERA);
                return;
            } else {
                takePic();//调用具体方法
            }
        } else {
            takePic();//调用具体方法
        }
    }
    @Override
    public void onBackPressed() {
        checkInput();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //
//        super.onSaveInstanceState(outState);
    }
}
